package campus.aiit.ssl.config;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.HttpMethod;
import java.io.IOException;

/**
 * @author ihaokun
 * @date 2019/12/3 8:59
 * @see <a href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS">CORS 详解</a>
 * @see <a href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers">HTTP Headers 详解</a>
 */
public class CorsFilter implements Filter {

  @Override
  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) servletRequest;
    HttpServletResponse resp = (HttpServletResponse) servletResponse;
    // 以下请求头配置均可在@see的site中查看详细说明
    resp.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Accept, Content-Type, Authorization");
    resp.setHeader("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, DELETE, PATCH, HEAD.TRACE");
    resp.setHeader("Access-Control-Allow-Credentials","true");// 是否允许浏览器携带用户身份信息（cookie）
//    resp.setHeader("Access-Control-Allow-Origin", "*");//XXX 前期调试可以设置为*，后面部署为了安全要修改为指定前端部署host；注意：若WithCredentials，不能为*
    resp.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8081");
//    resp.setHeader("Access-Control-Allow-Origin", "null");
    if (req.getMethod().equals(HttpMethod.OPTIONS)) {
      resp.getWriter().print("success");
    } else {
      filterChain.doFilter(req, resp);
    }
  }

}